/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.mall.util.jsp.JspCacheManager
   Module Description   :

   Date Created      : 2010/1/7
   Original Author   : andy.chuang
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.mall.util.jsp;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * @author andy.chuang
 *
 */
public class JspCacheManager {
//    private static Map<String, Long> timeoutMap=new HashMap<String, Long>();
//    private static Map<String, Long> cachedTimeMap=new HashMap<String, Long>();
//    private static Map<String, String> cacheMap=new HashMap<String, String>();
    private Logger LOGGER=LoggerFactory.getLogger(JspCacheManager.class);
    private String cacheFolder;
    /**
     * @return the cacheFolder
     */
    public String getCacheFolder() {
        return cacheFolder;
    }
    /**
     * @param cacheFolder the cacheFolder to set
     */
    public void setCacheFolder(String cacheFolder) {
        this.cacheFolder = cacheFolder;
    }
    
    public String getKey(String cacheKey, String url, String appendParameter, Map requestMap){
	if(requestMap==null)requestMap=new HashMap();
	String uri=null;
	if(url.indexOf("?")>0){
	    uri=url.substring(0, url.indexOf("?"));
	}else{
	    uri=url;
	}
	String queryString="";
	if(url.indexOf("?")>0){
	   queryString=url.substring(url.indexOf("?")+1, url.length());
	}
	StringBuffer sb=new StringBuffer("");
	if(cacheKey!=null){
	    sb.append(cacheKey);
	}else{
	    sb.append(uri);
	}
	if(appendParameter!=null){
	    String[] parameters=appendParameter.split(",");
	    String[] queryStringSplit=queryString.split("&");
	    for(int i=0;i<queryStringSplit.length;i++){
		String[] pvPair=queryStringSplit[i].split("=");
		if(pvPair.length>1)
		requestMap.put(pvPair[0], pvPair[1]);
	    }
	    sb.append("Q");
	    for(int i=0;i<parameters.length;i++){
		if(i!=0){
		    sb.append("A");
		}
		sb.append(parameters[i]).append("E");
		
		String value=null;
		if(requestMap.get(parameters[i]) instanceof String[]){
		    value=((String[])requestMap.get(parameters[i]))[0];
		}else{
		    value=(String)requestMap.get(parameters[i]);
		}
		
		if(value!=null)sb.append(value);
	    }
	}
	String key=sb.toString();
	key=key.replaceAll("/", "S");
	return key;
    }
    public static void main(String args[]){
	JspCacheManager jc=new JspCacheManager();
	Map requestMap=new HashMap();
	requestMap.put("a1", "v1");
	String key=jc.getKey(null, "test.do?p1=2&p2=3", "p1,a1", requestMap);
	System.out.println(key);
	System.out.println(key.indexOf("?"));

    }
    public void addCache(String key, String content){
	try{
	saveFile(key, content);
	}catch(Exception e){
	    e.printStackTrace();
	    LOGGER.warn("add cache failed! key:"+key);
	}
	
    }
    public File getContent(String cacheKey, String url, String appendParameter, Map requestMap){
	return new File(cacheFolder+"/"+getKey(cacheKey, url, appendParameter, requestMap)+".htm");
    }
    public synchronized void saveFile(String key, String content)throws Exception{
	if(content==null || content.indexOf("The requested resource")>=0){
	    LOGGER.warn("The requested resource is not available");
	    return;
	}
	File folder=new File(cacheFolder);
	if(!folder.exists()){
	    folder.mkdirs();
	}
	String savePath=cacheFolder+"/"+key+".htm";
	
        File file=new File(savePath);
        if(!file.exists()){
    		file.createNewFile();
    	}
    	InputStream is=new ByteArrayInputStream(content.getBytes());
    	OutputStream os=new FileOutputStream(savePath);
    	int length=0;
    	if(is!=null)  {
    		byte[] buf = new byte[8192];
    		
    		while (((length = is.read(buf)) != -1))  {	
    			
    			os.write(buf,0, length);		
    		}		 
    		is.close();	 
    		
    		os.flush();
    		os.close();
    		is.close();
    	}
    }

}
